<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px" v-if="MapSta">
      <el-form-item label="配送专员" prop="wxName">
        <el-input v-model="queryParams.wxName" :readonly='true' clearable style="width: 180px"
          v-if="queryParams.wxName !=undefined" />
        <el-button text type="primary" @click="addZY"
          v-if="queryParams.wxName ==undefined">添加</el-button>
      </el-form-item>
      <el-form-item label="电话号码" prop="Phone" v-if="queryParams.wxName !=undefined">
        <el-input v-model="queryParams.Phone" :readonly='true' clearable style="width: 180px" />
        <el-button text type="primary" @click="addZY">修改</el-button>
      </el-form-item>
      <el-form-item label="专员名称" prop="accName">
        <el-input v-model="queryParams.accName" placeholder="请输入专员名称" clearable
          style="width: 180px" />
      </el-form-item>
      <el-form-item label="地市主管" prop="attache">
        <el-select v-model="queryParams.preBec" placeholder="请选择地市主管" clearable style="width: 200px"
          @change='preBecSelEvents'>
          <el-option v-for="item in preBecSel" :key="item.id" :label="item.accountName"
            :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="区域名称" prop="areaName">
        <el-input v-model="queryParams.areaName" placeholder="请入区域名称" clearable
          style="width: 200px" />
      </el-form-item>
    </el-form>
    <div class="map">
      <div id="container"></div>
      <div class="input-card" v-if="MapSta">
        <el-button type="primary" plain @click="drawPolygon" style="margin-bottom: 5px"
          v-if="mapDrawSta">绘制多边形</el-button>
        <!-- <el-button type="primary" plain @click="editorPolygon" style="margin-bottom: 5px"
          v-if="mapDrawSta==false">编辑多边形</el-button> -->
        <el-button type="primary" plain @click="empty" v-if="mapDrawSta==false"
          style="margin-bottom: 5px">清空</el-button>
        <el-button type="primary" plain @click="saveEditedPolygon" style="margin-bottom: 5px"
          :disabled="!editMode" v-if="mapDrawSta==false">保存区域</el-button>
        <!-- <el-button type="primary" plain @click="saveEditedPolygon"
          style="margin-bottom: 5px">关闭并</el-button> -->
      </div>
    </div>
    <el-dialog v-model="innerDrawer" title="配送专员" width="500" :append-to-body="true"
      :close-on-click-modal='false' :before-close="handleClose">
      <el-form :model="form">
        <el-form-item label="配送专员" :label-width="formLabelWidth">
          <el-input v-model="form.phonenumber" autocomplete="off" :minlength='11' :maxlength='11'
            placeholder='请输入手机号'>
            <template #append>
              <el-button :icon="Search" @click="sechPSPhone" />
            </template>
          </el-input>
        </el-form-item>
        <div v-if="form.Phone !=undefined">
          <el-form-item label="微信昵称" :label-width="formLabelWidth">
            <el-input v-model="form.wxName" autocomplete="off" :readonly='true'
              placeholder='请输入微信昵称' />
          </el-form-item>
          <el-form-item label="联系电话" :label-width="formLabelWidth">
            <el-input v-model="form.Phone" autocomplete="off" :readonly='true'
              placeholder='请输入联系电话' />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="innerDrawerCol">取消</el-button>
          <el-button type="primary" @click="submitForm">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { Back, Search } from "@element-plus/icons-vue";
import { beChargeSel, saveArea } from "@/api/director/attache";
import AMapLoader from "@amap/amap-jsapi-loader";
import { onMounted, ref, inject } from "vue";
import { shallowRef } from "@vue/reactivity";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
const { proxy } = getCurrentInstance();
const formLabelWidth = ref("140px");
const preBecList = inject("preBecList");
const coordinatesList = inject("coordinatesList");
const preBecSel = ref([]);
const attacheSel = ref([]);

const map = shallowRef(null);
const mouseTool = shallowRef(null);
const polyEditor = shallowRef(null);

const dataMap = reactive({
  form: {
    phonenumber: undefined,
    wxName: undefined,
    Phone: undefined,
    openid: undefined,
  },
  queryParams: {
    //  搜索条件
    wxName: undefined,
    Phone: undefined,
    accName: undefined,
    preBec: undefined,
    areaName: undefined,
    openid: undefined,
    userType: userStore.userDta.userType,
    id: userStore.userDta.id,
  },
});
const { queryParams, form } = toRefs(dataMap);

function reset() {
  form.value = {
    phonenumber: undefined,
    wxName: undefined,
    Phone: undefined,
    openid: undefined,
  };
  zyShe.value = true;
  proxy.resetForm("userRef");
}
function innerDrawerCol() {
  reset();
  innerDrawer.value = false;
}
const polygonOverlay = shallowRef(null);
const editMode = ref(false);
const innerDrawer = ref(false);

// 关闭弹框
function handleClose() {
  reset();
  innerDrawer.value = false;
}
// 专员弹框
function addZY() {
  innerDrawer.value = true;
}
const zyShe = ref(true);
// 配送专员手机号搜索
function sechPSPhone() {
  console.log(form.value.phonenumber.length);
  if (form.value.phonenumber.length != 11) {
    ElMessage({
      message: "请输入正确手机号",
      type: "warning",
      duration: 2 * 1000,
    });
    return false;
  }
  beChargeSel({ phone: form.value.phonenumber }).then((res) => {
    console.log(res.data.openid, "这啥");
    if (res.status == 200) {
      form.value.wxName = res.data.nickname;
      form.value.Phone = res.data.phone;
      form.value.openid = res.data.openid;
      queryParams.value.openid = res.data.openid;
      zyShe.value = false;
    } else {
      ElMessage({
        message: res.msg,
        type: "warning",
        duration: 2 * 1000,
      });
    }
  });
}
function submitForm() {
  if (zyShe.value) {
    ElMessage({
      message: "请搜索配送员",
      type: "warning",
      duration: 2 * 1000,
    });
    return false;
  }
  queryParams.value.wxName = form.value.wxName;
  queryParams.value.Phone = form.value.Phone;
  reset();
  innerDrawer.value = false;
}
function calculatePolygonCenter(points) {
  let totalX = 0;
  let totalY = 0;
  let pointCount = points.length;

  // 遍历所有点，累加坐标
  points.forEach((point) => {
    totalX += point.x;
    totalY += point.y;
  });

  // 计算平均坐标
  const centerX = totalX / pointCount;
  const centerY = totalY / pointCount;

  return { centerX, centerY };
}
const polygons = ref([]);
const arrMark = ref([]);

const examineMapSta = inject("examineMapSta");
const MapSta = ref(true);
watch(
  () => examineMapSta.value,
  (newValue) => {
    MapSta.value = newValue;
  },
  { deep: true }
);
const mapSelFals = inject("mapSelFals");
const AMapMAP = ref("");

watch(
  () => mapSelFals.value,
  (newValue, old) => {
    polygons.value = [];
    arrMark.value = [];
    for (let i = 0; i < coordinatesList.value.length; i++) {
      polygons.value.push({
        path: coordinatesList.value[i].deliveryScope,
        // strokeColor: '#FF0000',
        // strokeOpacity: 0.8,
        // strokeWeight: 2,
        // fillColor: '#FF0000',
        fillOpacity: 0.35,
      });
      let artu = calculatePolygonCenter(
        coordinatesList.value[i].deliveryScopexy
      );
      arrMark.value.push({
        position: [artu.centerY, artu.centerX],
        content: coordinatesList.value[i].accountName,
        districtNameS: coordinatesList.value[i].districtName,
      });
    }
    if (AMapMAP.value) {
      markMap();
    } else {
      setTimeout(() => {
        markMap();
      }, 1000);
    }
  }
);
onMounted(() => {
  MapSta.value = examineMapSta.value;
  mapInit();
  preBecSel.value = preBecList.value;
});
const mapDrawSta = ref(true);
const mapInit = () => {
  window._AMapSecurityConfig = {
    securityJsCode: "8a17867969936026b41139d7510e363d", // 密钥
  };
  AMapLoader.load({
    key: "d9f8b9cbb3315f44eb0f29d35733bb1f",
    // version:"2.0",
    plugins: [],
  })
    .then((AMap) => {
      map.value = new AMap.Map("container", {
        viewMode: "3D",
        zoom: 12,
        // center: [113.74632, 34.748715], //初始化地图中心点位置
      });

      AMap.plugin(
        [
          "AMap.Scale",
          "AMap.ToolBar",
          "AMap.HawkEye",
          "AMap.MapType",
          "AMap.MouseTool",
          "AMap.PolyEditor",
          "AMap.DistrictSearch",
        ],
        function () {
          const scale = new AMap.Scale();
          map.value.addControl(scale);
          map.value.addControl(new AMap.ToolBar());
          map.value.addControl(new AMap.HawkEye());
          map.value.addControl(new AMap.MapType());
        }
      );
      AMapMAP.value = AMap;

      mouseTool.value = new AMap.MouseTool(map.value);

      map.value.on("dblclick", function (ev) {
        // 地图点击事件
        setTimeout(() => {
          editorPolygon();
        }, 500);
      });
      map.value.on("rightclick", function (event) {
        // event.lnglat 获取点击的经纬度坐标
        setTimeout(() => {
          editorPolygon();
        }, 500);
      });
    })
    .catch((e) => {
      console.log(e);
    });
};
const polygonsMap = ref([]); // 用于存储多边形实例的数组
const markerText = ref([]);
// 渲染专员区域
function markMap(sta) {
  let AMap = AMapMAP.value;
  polygonsMap.value.forEach((polygon) => {
    polygon.setPath([]); // 清空多边形路径
  });
  markerText.value.forEach((marText) => {
    marText.setText("");
  });
  polygonsMap.value = [];
  markerText.value = [];
  for (let i = 0; i < polygons.value.length; i++) {
    // 创建多边形示例,'
    const polygon = new AMap.Polygon({
      map: map.value,
      path: polygons.value[i].path,
      // strokeColor: "black",
      // strokeWeight: 2,
      // fillColor: "red",
      fillOpacity: 0.3,
    });
    polygonsMap.value.push(polygon); // 添加到多边形数组中
  }

  for (let i = 0; i < arrMark.value.length; i++) {
    const markerText1 = new AMap.Text({
      text:
        "负责人：" +
        arrMark.value[i].content +
        "\n区域：" +
        arrMark.value[i].districtNameS,
      position: new AMap.LngLat(
        arrMark.value[i].position[0],
        arrMark.value[i].position[1]
      ), // 文字在多边形上的位置
      style: {
        "font-size": "10px",
        "white-space": "pre-wrap", // 使文本换行
        "font-weight": "bold",
        "text-align": "left",
      },
      map: map.value,
    });
    markerText.value.push(markerText1);
  }
  map.value.setFitView();
}

function preBecSelEvents(e) {
  emit("load-data", e);
  if (e != "") {
    clearBoundaries();
    for (let i = 0; i < preBecSel.value.length; i++) {
      if (e == preBecSel.value[i].id) {
        regionalism(preBecSel.value[i].warehouseCoverage, 1);
        break;
      }
    }
  } else {
    clearBoundaries();
  }
}
const boundaries = ref([]);
let arrPolygon = [];
// 清空边界的函数
function clearBoundaries() {
  for (let i = 0; i < arrPolygon.length; i++) {
    map.value.remove(arrPolygon[i]); //清除上次结果
  }
  map.value.setFitView();
}
// 行政区域查询
function regionalism(arrList, sta) {
  let AMap = AMapMAP.value;
  boundaries.value = arrList;
  boundaries.value.forEach((boundaryData) => {
    const boundary = new AMap.DistrictSearch({
      level: "district", // 查询级别为城市
      extensions: "all", // 返回行政区边界坐标组等信息
    });
    boundary.search(boundaryData.county, (status, result) => {
      if (status === "complete") {
        if (result.districtList && result.districtList.length) {
          const bounds = result.districtList[0].boundaries;
          if (bounds) {
            for (let i = 0, l = bounds.length; i < l; i++) {
              const polygon = new AMap.Polygon({
                path: bounds[i],
                // strokeColor: "blue",
                // strokeWeight: 2,
                // fillOpacity: 0.4,
                // fillColor: "rgba(0,0,255,0.3)",
                strokeColor: "#35fffd",
                strokeOpacity: 1,
                strokeWeight: 1,
                fillColor: "#35fffd",
                fillOpacity: 0.15,
                strokeStyle: "solid",
                zIndex: 10,
              });
              arrPolygon.push(polygon);

              map.value.add(polygon);
              map.value.setFitView();
            }
          }
        }
      }
    });
  });
}

// 绘制多边形
const drawPolygon = () => {
  if (mouseTool.value) {
    mapDrawSta.value = null;
    mouseTool.value.polygon();
    mouseTool.value.on("draw", function (event) {
      polygonOverlay.value = event.obj;
      mouseTool.value.close();
    });
  }
};

// 多边形编辑
const editorPolygon = () => {
  let AMap = AMapMAP.value;
  if (polygonOverlay.value) {
    if (polygonOverlay.value.De.path.length != 0) {
      mapDrawSta.value = false;
    } else {
      ElMessage({
        message: "区域不能少于三个点",
        type: "warning",
        duration: 2 * 1000,
      });
      mapDrawSta.value = true;
      return false;
    }

    if (!polyEditor.value || polyEditor.value) {
      // 创建多边形编辑工具
      polyEditor.value = new AMap.PolyEditor(map.value, polygonOverlay.value);
    }
    // 进入编辑模式
    polyEditor.value.open();
    editMode.value = true;
  } else {
    ElMessage({
      message: "区域不能少于三个点",
      type: "warning",
      duration: 2 * 1000,
    });
    return false;
  }
};
// 清空
const empty = () => {
  mapDrawSta.value = true;
  polygonOverlay.value.setPath([]);

  mouseTool.value.close(); //关闭，并清除覆盖物
  editMode.value = false;
};
const emit = defineEmits(["load-data"]);
// 保存编辑后的多边形
const saveEditedPolygon = () => {
  if (queryParams.value.wxName == undefined) {
    ElMessage({
      message: "请选择配送专员",
      type: "warning",
      duration: 2 * 1000,
    });
    return false;
  }
  if (queryParams.value.accName == undefined) {
    ElMessage({
      message: "请输入专员名称",
      type: "warning",
      duration: 2 * 1000,
    });
    return false;
  }
  // if (queryParams.userType == 11) {
  if (queryParams.value.preBec == undefined) {
    ElMessage({
      message: "请选择地市主管",
      type: "warning",
      duration: 2 * 1000,
    });
    return false;
  }
  // }
  if (queryParams.value.areaName == undefined) {
    ElMessage({
      message: "请入区域名称",
      type: "warning",
      duration: 2 * 1000,
    });
    return false;
  }

  let datalonlat = {
    openid: queryParams.value.openid,
    districtName: queryParams.value.areaName,
    accountName: queryParams.value.accName,
    phone: queryParams.value.Phone,
    coordinates: [],
    functionaryId: queryParams.value.preBec,
  };
  // if (queryParams.value.userType == 11) {
  // datalonlat.functionaryId = queryParams.value.preBec;
  // } else {
  //   datalonlat.functionaryId = queryParams.value.id;
  // }
  const lonlatList = polygonOverlay.value.getPath();
  for (let i = 0; i < lonlatList.length; i++) {
    datalonlat.coordinates.push({
      latitude: lonlatList[i].lat,
      longitude: lonlatList[i].lng,
    });
  }
  datalonlat.coordinates = JSON.stringify(datalonlat.coordinates);
  saveArea(datalonlat).then((res) => {
    console.log(res, "这是数据");
    if (editMode.value && polyEditor.value) {
      // 退出编辑模式
      polyEditor.value.close();
      editMode.value = false;
    }
    reset();
    queryParams.value = {
      //  搜索条件
      wxName: undefined,
      Phone: undefined,
      accName: undefined,
      preBec: undefined,
      areaName: undefined,
      openid: undefined,
      userType: userStore.userDta.userType,
      id: userStore.userDta.id,
    };
    innerDrawer.value = false;
    mapDrawSta.value = true;
    emit("load-data", "关闭");
    empty();
    clearBoundaries();
    ElMessage({ message: "添加成功", type: "success", duration: 2 * 1000 });
  });
};

// 关闭用户弹窗组件
const handleCloseMap = () => {
  if (editMode.value && polyEditor.value) {
    // 退出编辑模式
    polyEditor.value.close();
    editMode.value = false;
  }
  reset();
  queryParams.value = {
    //  搜索条件
    wxName: undefined,
    Phone: undefined,
    accName: undefined,
    preBec: undefined,
    areaName: undefined,
    openid: undefined,
    userType: userStore.userDta.userType,
    id: userStore.userDta.id,
  };
  innerDrawer.value = false;
  emit("load-data", "关闭right");
  if (polygonOverlay.value) {
    empty();
  }
  if (mapDrawSta.value == null) {
  }
  clearBoundaries();
};
// 子组件默认包含是私有
defineExpose({
  handleCloseMap,
});
</script>

<style scoped lang="scss">
#container {
  width: 100%;
  height: 700px;
}
</style>